package com.yhc.user.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yhc.common.dto.BaseResult;
import com.yhc.common.dto.UserCacheInfo;
import com.yhc.order.api.OrderApi;
import com.yhc.order.api.request.OrderSaveRequest;
import com.yhc.order.api.response.OrderSaveResponse;
import com.yhc.user.api.request.BuyGoodsRequest;
import com.yhc.user.server.entity.UserWalletEntity;
import com.yhc.user.server.exception.ErrorCodeEnum;
import com.yhc.user.server.exception.UserServiceException;
import com.yhc.user.server.mapper.base.UserWalletMapper;
import com.yhc.user.server.plugin.RedisService;
import com.yhc.user.server.service.IUserCacheService;
import com.yhc.user.server.service.IUserService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserWalletMapper userWalletMapper;

    @Autowired
    IUserCacheService userCacheService;

    @Autowired
    OrderApi orderApi;

    @Autowired
    RedisService redisService;

    @Override
    public String login(Long id) {

        // 此处应校验账号密码，根据实际情况处理
        UserWalletEntity userWallet = userWalletMapper.selectById(id);
        if(userWallet == null){
            throw new UserServiceException(ErrorCodeEnum.EXCEPTION_USER_NO_EXISTS);
        }

        final String tk = "test";

        UserCacheInfo userCacheInfo = new UserCacheInfo();
        userCacheInfo.setUserId(userWallet.getUserId());
        redisService.set(userWallet.getUserId() + "", tk, 60 * 60L);
        redisService.set(tk, userCacheInfo, 60 * 60L);
        return tk;
    }

    @Override
    @GlobalTransactional
    public Long buy(BuyGoodsRequest request) {

        log.info("# seata xid:{}", RootContext.getXID());

        Long userId = userCacheService.getUserIdWithException();

        LambdaQueryWrapper<UserWalletEntity> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(UserWalletEntity::getUserId,userId);
        UserWalletEntity userWallet = userWalletMapper.selectOne(userQueryWrapper);
        userWallet.setAmount(userWallet.getAmount() - request.getAmount());

        // 扣减余额
        userWalletMapper.updateById(userWallet);

        // 下单
        OrderSaveRequest orderSaveRequest = OrderSaveRequest.builder().amount(request.getAmount()).build();
        BaseResult<OrderSaveResponse> result = orderApi.save(orderSaveRequest);
        if (result.isSuccess()) {

            // 验证分布式事务回滚
            if (false) {
                throw new RuntimeException("test txc rollback");
            }

            return result.getData().getOrderId();
        }

        throw new UserServiceException(ErrorCodeEnum.EXCEPTION_BUG_GOODS);
    }
}
